import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import ElementUI from '../components/ElementUI.vue'
import Home from '../components/Home.vue'
import User from '../components/user/user.vue'
import Welcome from '../components/Welcome.vue'
import ItemCat from '../components/items/ItemCat.vue'
import Item from '../components/items/Item.vue'
import AddItem from '../components/items/addItem.vue'
Vue.use(VueRouter)
//如果需要在组件内部展现路由组件,则应该使用children属性
const routes = [
  {path: '/', redirect: '/login'},
  {path: '/login', component: Login},
  {path: '/elementUI', component: ElementUI},
  {path: '/home', component: Home, redirect: '/welcome',
    children:[
      {path: '/welcome', component: Welcome},
      {path: '/user', component: User},
      {path: '/itemCat', component: ItemCat},
      {path: '/item', component: Item},
      {path: '/item/addItem',component: AddItem}
    ]},
]

const router = new VueRouter({
  routes
})

/**
 * 设定路由导航守卫
 * 参数说明: 1.to 要访问的路径  2.from 从哪个路径来 3.next请求放行
 * 策略: 1.用户访问/login 放行请求.
 *       2.如果用户没有访问登录页 则校验用户是否登录. 校验token
 *        有token   应该放行
 *        没有token 应该跳转到登陆页面
 * 路由导航守卫 相当于一个拦截器 拦截/放行
 */
router.beforeEach((to,from,next) => {
    if(to.path === '/login') return next()
    //如果用户访问的网址不是/login 获取token
    let token = window.sessionStorage.getItem("token")
    //if(token !=null && token.length>0)  token如果有值
    if(token) return next()
    //如果程序执行到这一行 说明token没有数据. 跳转到登陆页面
    next("/login")
})


//对外声明路由对象 子组件向父组件传递数据.
export default router
